import { OneModal } from '@/components/one-ui';
import { IOneModalRef } from '@/pages/type';
import { Ref, useEffect, useRef } from 'react';
import { AnnounceManageAPI } from '../common/type';
import pageStyles from '@/common/pageLayout.less';
import { Col, Form, Input, message, Row, Select, Spin, TreeSelect } from 'antd';
import {
  getCompanyID,
  getDeptPosTreeIcon,
  getPosIDs,
  getTenantID,
  getUserDepID,
  getUserID,
  loopArray,
} from '@/utils';
import MyIcon from '@/components/MyIcon';
import {
  getFlowOrgTreeByOrgIDService,
  getUserDataList,
} from '@/services/BaseLayout';
import { addCheckService } from '../service';

export const AnnounceCheckModal: React.FC<AnnounceManageAPI.IAnnounceCheckModal> = ({
  onClose,
  isShowModal, //是否显示modal
  checkRows,
  reloadAnnounce,
}) => {
  const checkModalRef: Ref<IOneModalRef> = useRef(null); //弹框的ref
  const [checkForm] = Form.useForm(); //表单 form

  /* 关闭弹窗 */
  const onCloseModal = () => {
    if (checkModalRef) {
      if (checkModalRef.current) {
        if (checkModalRef.current.onModalCancel) {
          checkModalRef.current.onModalCancel();
        }
      }
    }
  };

  /**获取组织机构树 接口 */
  const {
    getFlowOrgTreeRun,
    getFlowOrgTreeLoading,
    getFlowOrgList,
  } = getFlowOrgTreeByOrgIDService();
  const { getUserRun, getUserLoading, getUserList } = getUserDataList(
    (res: any) => {
      if (!(res && res?.msgFlag)) {
        message.error(res?.msg);
      }
    },
  );

  /**
   * 初始化获取组织机构树
   */
  useEffect(() => {
    if (isShowModal) {
      let payload = {
        params: '0',
        flowType: '2',
        orgID: getPosIDs(),
      };
      getFlowOrgTreeRun(payload);
    }
  }, [isShowModal]);

  // 处理树数据
  const orgTreeData = (data: any[]): any[] => {
    return data?.map((item: any) => {
      return {
        ...item,
        title: (
          <div>
            {getDeptPosTreeIcon(String(item?.textType))}
            {item?.text}
          </div>
        ),
        searchtitle: item?.text,
        key: item?.id,
        value: item?.id,
        children:
          item?.children && item?.children?.length > 0
            ? orgTreeData(item?.children)
            : null,
        disabled: item?.textType == '2' ? false : true,
      };
    });
  };

  /**处理树选中后获取用户的参数
   * @param list 传入的选中书id
   * @returns
   */
  const handleGetId = (list: any[]) => {
    let paramsIDS: any = []; //参数保存
    let checkRow = list[0]; //点击选中的节点

    // 递归树
    let loop = (treeData: any[]) => {
      treeData?.forEach((item: any) => {
        if (item?.children && item?.children?.length > 0) {
          loop(item?.children);
        }
        if (checkRow?.textType == item?.textType) {
          paramsIDS?.push(item?.id);
        }
      });
    };
    loop(list);
    let idsString = paramsIDS?.join('|');
    if (checkRow?.textType == 0) {
      return { userCompanyID: idsString };
    } else if (checkRow?.textType == 1) {
      return { userDepartmentID: idsString };
    } else if (checkRow?.textType == 2) {
      return { userPositionID: idsString };
    }
  };

  /**
   * 点击选中岗位
   * @param selectedKeys
   * @param selectedNodes
   */
  const onTreeSelect = (selectedKeys: any, selectedNodes: any) => {
    checkForm?.setFieldsValue({ ownerID: null });
    let userListPayload = handleGetId([selectedNodes]);
    getUserRun(userListPayload);
  };

  /**
   * 审核接口回调
   * @param res
   */
  const addCheckCallllback = (res: any) => {
    if (res && res?.msgFlag) {
      message.success(res?.msg);
      onCloseModal();
      reloadAnnounce();
    } else {
      message.error(res?.msg);
    }
  };

  /**
   * 引入审核接口
   */
  const { addCheckLoading, addCheckRun } = addCheckService(addCheckCallllback);

  /**
   * 保存
   */
  const saveCheck = () => {
    checkForm?.validateFields()?.then((values: any) => {
      let treeListPos: any[] = loopArray(getFlowOrgList);
      let checkUsrObj = treeListPos?.filter((item: any) => {
        return item?.id == values?.checkPositionID;
      });
      let useObj: any = checkUsrObj?.[0]?.attributes;
      let params = {
        id: checkRows?.id,
        versionNum: checkRows?.versionNum,
        state: `${getTenantID()}12021001`,
        check: {
          applyerID: getUserID(),
          applyPositionID: getPosIDs(),
          applyDepartmentID: getUserDepID(),
          applyCompanyID: getCompanyID(),
          checkerID: values?.checkerID,
          checkPositionID: values?.checkPositionID,
          checkDepartmentID: useObj?.departmentID,
          checkCompanyID: useObj?.companyID,
        },
      };

      addCheckRun(params);
    });
  };

  return (
    <>
      <OneModal
        open={true}
        getContainer={false}
        ref={checkModalRef}
        title={'提交审核'}
        width={document.body.clientWidth * 0.3}
        onCancel={onClose}
        bodyStyle={{
          padding: '5px 0px',
        }}
        centered
        onOk={saveCheck}
        confirmLoading={
          getFlowOrgTreeLoading || getUserLoading || addCheckLoading
        }
      >
        <Spin
          spinning={getFlowOrgTreeLoading || getUserLoading || addCheckLoading}
        >
          <div className={pageStyles['fromView-styles']}>
            <Form labelAlign="right" form={checkForm}>
              <Row>
                <Col span={24}>
                  <Form.Item
                    label="审核岗位"
                    name="checkPositionID"
                    rules={[
                      {
                        required: true,
                        message: '请选择审核岗位',
                      },
                    ]}
                  >
                    <TreeSelect
                      placeholder="请选择审核岗位"
                      showSearch
                      allowClear
                      treeNodeFilterProp={'searchtitle'}
                      treeData={orgTreeData(getFlowOrgList)}
                      onSelect={onTreeSelect}
                      loading={getFlowOrgTreeLoading}
                    />
                  </Form.Item>
                </Col>
                <Col span={24}>
                  <Form.Item
                    label="审核人"
                    name="checkerID"
                    rules={[
                      {
                        required: true,
                        message: '请选择审核人',
                      },
                    ]}
                  >
                    <Select
                      placeholder="请选择审核人"
                      loading={getUserLoading}
                      allowClear
                      showSearch
                      optionFilterProp={'searchtitle'}
                      disabled={getUserLoading}
                    >
                      {getUserList && getUserList?.length > 0 ? (
                        <>
                          {getUserList?.map((item: any) => {
                            return (
                              <Select.Option
                                disabled={
                                  item?.id == getUserID() ? true : false
                                }
                                value={item?.id}
                                key={item?.id}
                                searchtitle={item?.realName}
                              >
                                <MyIcon
                                  style={{ marginRight: 5 }}
                                  type="icon-lianxiren"
                                />
                                {item?.realName}
                              </Select.Option>
                            );
                          })}
                        </>
                      ) : (
                        <></>
                      )}
                    </Select>
                  </Form.Item>
                </Col>
                <Col span={24}>
                  <Form.Item label="申请原因" name="checkContent">
                    <Input.TextArea
                      placeholder={`请输入申请原因`}
                      showCount
                      maxLength={200}
                      autoSize={{ minRows: 2, maxRows: 4 }}
                    />
                  </Form.Item>
                </Col>
              </Row>
            </Form>
          </div>
        </Spin>
      </OneModal>
    </>
  );
};
